package com.oocl.server.controller.impl;

import java.io.OutputStream;
import java.net.ServerSocket;

import com.oocl.server.Server;
import com.oocl.server.controller.ServerController;
import com.oocl.server.dao.UserDao;
import com.oocl.server.dao.impl.UserDaoImpl;
import com.oocl.server.parser.impl.HtmlParserImpl;
import com.oocl.server.util.Logger;

public class ServerControllerImpl implements ServerController {

	// private ChatServer chatServer;

	private HtmlParserImpl parser;
	private UserDao userDao;
	private Server server;
	
	private long startTS = 0;

	public ServerControllerImpl(Server server) {
		this.parser = new HtmlParserImpl();
		userDao = new UserDaoImpl();
		this.server = server;
	}

	@Override
	public void turnOn(OutputStream out) {

		if(server==null){
			Logger.log("管理的聊天服务器为空");
			this.parser.send500Error("管理的聊天服务器为空", out);
			return;
		}
		
		// /判断ServerSocket是否断开了
		if (server.isClosed()) {
			server.start();// 开服务器
			
			//时间戳设置
			startTS = System.currentTimeMillis();
		}

		this.parser.setOnlineList(userDao.findAll())
				.setCurTime(System.currentTimeMillis()-startTS).genericHtml(true, out);
	}

	@Override
	public void refresh(OutputStream out) {
		
		if(server==null){
			Logger.log("管理的聊天服务器为空");
			this.parser.send500Error("管理的聊天服务器为空", out);
			return;
		}
		
		// 判断 server 是否开启
		// /如果开启了server ，就获取server的数据
		if (this.server.isClosed())
			this.parser.genericHtml(false, out);
		else
			this.parser.setOnlineList(userDao.findAll())
					.setCurTime(System.currentTimeMillis()- this.startTS)
					.genericHtml(true, out);
	}

	@Override
	public void turnOff(OutputStream out) {
		
		if(server==null){
			Logger.log("管理的聊天服务器为空");
			this.parser.send500Error("管理的聊天服务器为空", out);
			return;
		}
		
		// /判断ServerSocket是否断开了
		if (!server.isClosed()) {
			server.stop();// 关闭服务器
		}
		this.parser.genericHtml(false, out);
	}

}
